﻿using Microsoft.Practices.Unity.InterceptionExtension;
using Sapit.Helpers;
using Sapit.Unity.Attributes;

namespace Sapit.Unity
{
    public class RetryHandler : ICallHandler
    {
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            RetryAttribute retry = AttributeHelper.GetAttributeIfPresent<RetryAttribute>(input.MethodBase);
            if (retry != null)
            {
                int numberOfTries = 0;
                while (numberOfTries < retry.TimesToRetry || retry.TimesToRetry == 0)
                {
                    numberOfTries += 1;

                    IMethodReturn msg = getNext()(input, getNext);
                    if (msg.Exception != null)
                    {
                        if (numberOfTries == retry.TimesToRetry)
                        {
                            return msg;
                        }
                    }
                    else
                    {
                        return msg;
                    }
                }
                return null; // Will never be called
            }
            else
            {
                return getNext()(input, getNext);
            }
        }

        public int Order { get; set; }
    }
}
